package com.atguigu.cmsService.controller;


import com.atguigu.cmsService.entity.CrmBanner;
import com.atguigu.cmsService.entity.query.BannerQuery;
import com.atguigu.cmsService.service.CrmBannerService;
import com.atguigu.commonutils.R;
import com.baomidou.mybatisplus.core.toolkit.ObjectUtils;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import io.swagger.annotations.ApiOperation;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import java.util.Date;

/**
 * <p>
 * 首页banner表 前端控制器(后台管理使用)
 * </p>
 *
 * @author Mr.Alan
 * @since 2020-08-22
 */
@RestController
@RequestMapping("/cmsService/admin/banner")
@CrossOrigin
public class CrmBannerController {

    @Resource
    private CrmBannerService crmBannerService;


    @ApiOperation("更新轮播图信息")
    @PostMapping("/update")
    public R update(@RequestBody CrmBanner banner) {

        // 初始化值
        Date now = new Date();
        banner.setGmtModified(now);
        if (crmBannerService.updateById(banner)) {
            return R.ok("更新成功");
        }
        return R.error("更新失败");

    }

    @ApiOperation("添加一个轮播图")
    @PostMapping("/save")
    public R save(@RequestBody CrmBanner banner) {

        // 初始化值
        Date now = new Date();
        Integer count = crmBannerService.lambdaQuery().eq(CrmBanner::getTitle, banner.getTitle()).count();
        if (count > 0) {
            return R.error(String.format("标题 <%s> 已存在", banner.getTitle()));
        }
        banner.setGmtCreate(now)
                .setIsDeleted(false)
                .setGmtModified(now);
        if (crmBannerService.save(banner)) {
            return R.ok("添加成功");
        }
        return R.error("添加失败");

    }

    @PostMapping("/delete/{id}")
    @ApiOperation("通过ID删除轮播图")
    public R delete(@PathVariable("id") String id) {

        if (crmBannerService.remove(Wrappers.<CrmBanner>lambdaQuery().eq(CrmBanner::getId, id))) {
            return R.ok("删除成功");
        }
        return R.error("删除失败");

    }


    @PostMapping("/page")
    @ApiOperation("分页查询轮图")
    public R pageBanner(@RequestBody BannerQuery query) {

        Page<CrmBanner> page = new Page<>(query.getPageNum(), query.getPageSize());
        crmBannerService.lambdaQuery().like(ObjectUtils.isNotNull(query.getTitle()), CrmBanner::getTitle, query.getTitle())
                .between(ObjectUtils.isNotNull(query.getStartTime()) && ObjectUtils.isNotNull(query.getEndTime()),
                        CrmBanner::getGmtCreate, query.getStartTime(), query.getEndTime()).page(page);
        return R.ok().data("list", page.getRecords()).data("total", page.getTotal());

    }


}

